package com.lifp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.lifp.dto.EmployeeQueryParam;
import com.lifp.entity.Employee;
import com.lifp.service.EmployeeService;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 员工serviceImpl
 * @author lifp
 * @date 2024/05/29
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public Employee add(Employee employee) {
        Employee emp = mongoTemplate.save(employee);
        return emp;
    }

    public Integer update(Employee employee) {
        Query query = new Query(Criteria.where(Employee.Fields.id).is(employee.getId()));

        Update update = new Update();

        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Employee.class);
        long count = updateResult.getModifiedCount();

        return Integer.valueOf(String.valueOf(count));
    }

    public Integer deleteById(Long id) {
        return null;
    }

    public List<Employee> listEmployee(EmployeeQueryParam queryParam) {
        List<Employee> employees = mongoTemplate.find(generateQuery(queryParam), Employee.class);
        return employees;
    }

    /**
     * 构造查询条件
     * @param queryParam 查询参数
     * @return org.springframework.data.mongodb.core.query.Query
     * @date 2024/5/30
     * @author lifp
     **/
    private Query generateQuery(EmployeeQueryParam queryParam){
        Query query = new Query();

        Criteria criteria = new Criteria();

        if(queryParam.getId() != null){
            criteria.and(Employee.Fields.id).is(queryParam.getId());
        }
        if(StrUtil.isNotEmpty(queryParam.getName())){
            criteria.and(Employee.Fields.name).regex(queryParam.getName());
        }
        if(StrUtil.isNotEmpty(queryParam.getAddress())){
            criteria.and(Employee.Fields.address).regex(queryParam.getAddress());
        }

        if(queryParam.getStart() != null && queryParam.getEnd() != null){
            criteria.and(Employee.Fields.joinedDate).gte(queryParam.getStart()).lte(queryParam.getEnd());
        }else if(queryParam.getStart() != null){
            criteria.and(Employee.Fields.joinedDate).gte(queryParam.getStart());
        }else if(queryParam.getEnd() != null){
            criteria.and(Employee.Fields.joinedDate).lte(queryParam.getEnd());
        }

        return query.addCriteria(criteria);
    }
}
